﻿using SecureDataCMS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SecureDataCMS.Controllers
{
    public class ControlPanelController : Controller
    {
        //
        // GET: /ControlPanel/

        private SECCMS_liveEntities myDB = new SECCMS_liveEntities();
        const int ADMINISTRATORTYPE = 1;
        const int APPROVERTYPE = 2;
        const int PRIMARYINVTYPE = 3;
        const int DATAMANAGERTYPE = 5;
        const int RESEARCHERTYPE = 4;

        
        public tblUser LoginCheck(int type) //Function that validates logins. Copypaste between classes.
        {
            HttpCookie logCookie = Request.Cookies["loginCookie"];
            var listOfLogs = myDB.tblLogins.ToList();
            //int validLogin = 0; //invalid to begin with
            tblUser logReturn = null;

            if(logCookie == null)
            {
                return null;
            }
            
           foreach(var log in listOfLogs)
            {
                if (log.LoginKey.ToString().Equals(logCookie.Value) && DateTime.Compare(log.dtmCreated.AddHours(log.intHoursValid), DateTime.Now) >= 0 && log.tblUser.UserTypeID == type) //If their cookie is matching, still valid, and they are an approver
                {
                    //validLogin = 1; //They must be an approver of some kind.
                    logReturn = log.tblUser;
                }

            }
            return logReturn;
        }

        public ActionResult UserManagement()
        {
            tblUser theUser=null;
            int i=1;
            while(theUser == null && i<6)
            {
                theUser = LoginCheck(i);
                i++;
            } //Lol. Best login ever
            if(theUser == null)
            {
                return Redirect("/");
            }

            ViewBag.User = theUser;
            ViewBag.Departments = myDB.tblDepartments.ToList();
            
            return View();
        }

        public ActionResult UpdateUserDetails()
        {
            tblUser theUser = null;
            int i = 1;
            while (theUser == null && i < 6)
            {
                theUser = LoginCheck(i);
                i++;
            } //Lol. Best login ever
            if (theUser == null)
            {
                return Redirect("/");
            }

            if(Request.Form["passone"].Equals(Request.Form["passtwo"]))
            {
                theUser.strFirstName = Request.Form["FirstName"];
                theUser.strLastName = Request.Form["LastName"];
                theUser.strEmail = Request.Form["Email"];
                theUser.DepartmentID = Convert.ToInt32(Request.Form["Department"]);
            }
            else
            {
                if (Request.Form["passone"].Equals(""))
                {
                    theUser.strFirstName = Request.Form["FirstName"];
                    theUser.strLastName = Request.Form["LastName"];
                    theUser.strEmail = Request.Form["Email"];
                    theUser.DepartmentID = Convert.ToInt32(Request.Form["Department"]);
                }
            }
            UpdateModel(theUser);
            myDB.SaveChanges();
            return Redirect("/ControlPanel/UserManagement");
        }

        public ActionResult Index()
        {
            return Redirect("/"); //Go home browser, you're drunk
        }

        public ActionResult Approver()
        {
            HttpCookie theCookie = Request.Cookies["loginCookie"];
            int key = Convert.ToInt32(theCookie.Value);
            tblUser myUser = LoginCheck(APPROVERTYPE);
            if(myUser == null)
            {
                return Redirect("/");
            }
            var listOfRequests = (from p in myDB.tblRequests
                                  orderby p.dtmCreated descending
                                  select p).ToList(); // get this department's requests
            ViewBag.ListOfReqs = listOfRequests;
            ViewBag.UserName = myUser.strFirstName + " " + myUser.strLastName;

            return View();
        }

        
        public ActionResult approveStorage()
        {
            //this method is called when the approve storage button is clicked
            //this changes the database to show the data has been approved

            //changes item.approved and approval date
            //but not completed

            //get current time
            //stick it in the correct part of the database

            tblUser user = LoginCheck(APPROVERTYPE);
            if (user == null)
            {
                return Redirect("/");
            }
            var currTime = DateTime.Now;
            var jobID = Request.Form["inputJob"];
            

            tblRequest currRequest = null; //Oh wait, we need this don't we?

            int id;
            tblRequest request;
            if(int.TryParse(jobID, out id))
            {
                var requests = (from r in myDB.tblRequests
                                where r.RequestID == id
                                select r);
                if (requests.Count() == 0)
                    throw new Exception("No matching requests");
                else
                    request = requests.First();
            }
            else
                throw new Exception("Can't parse form. Something is very wrong with your browser. Are you using IE6 or something?");
            currRequest = request; //BWA HAHAHAHAHA

            
            if (currRequest == null)
            {
                return Redirect("/ControlPanel/Approver"); // This should go to an error page. You there! Programmer! Error Page! :)
            }
            //Now we have the job in question. Hooray. And I is the right number :D
            currRequest.intUserApprover = user.UserID;
            currRequest.dtmApproved = currTime;

            UpdateModel(currRequest);
            myDB.SaveChanges(); //???

            var Pi = (from T in myDB.tblUsers
                            where T.UserID == currRequest.intUserCreator
                            select T);

            var thePi = Pi.Single();

            string[] lines = { "From: securecms@polynubstudios.com", "To: " + thePi.strEmail, "Subject: New Project Approved", "Your project has been approved by " + user.strFirstName + user.strLastName, "." };

            System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines);

            var admin = (from T in myDB.tblUsers
                         where T.tblUserType.UserTypeID == 1
                         select T);

            var theAdmin = admin.Single();
            string[] lines2 = { "From: securecms@polynubstudios.com", "To: " + theAdmin.strEmail, "Subject: New Project approved", "A project approved by " + user.strFirstName + " " + user.strLastName + " needs actioning", "." };
           // myDB.Entry()
           // myDB.Entry(item).State = System.Data.EntityState.Modified;
              // myDB.SaveChanges();
            return Redirect("/ControlPanel/Approver");

               
        }

        public ActionResult denyStorage()
        {
            //this method is called when the deny storage button is clicked
            //this changes the database to show the data has been denied
            //should archive the request... but as of yet, such functionality does not exist
            //so it deletes it
            
            tblUser user = LoginCheck(APPROVERTYPE);
            if (user == null)
            {
                return Redirect("/");
            }
            var currTime = DateTime.Now;
            var jobID = Request.Form["inputJob"];


            tblRequest currRequest = null; //Oh wait, we need this don't we?

            int id;
            tblRequest request;
            if (int.TryParse(jobID, out id))
            {
                var requests = (from r in myDB.tblRequests
                                where r.RequestID == id
                                select r);
                if (requests.Count() == 0)
                    throw new Exception("No matching requests");
                else
                    request = requests.First();
            }
            else
                throw new Exception("Can't parse form. Something is very wrong with your browser. Are you using IE6 or something?");
            currRequest = request; //BWA HAHAHAHAHA


            if (currRequest == null)
            {
                return Redirect("/ControlPanel/Approver"); // This should go to an error page. You there! Programmer! Error Page! :)
            }
            //Now we have the job in question. Hooray. And I is the right number :D

            var piEmail = currRequest.tblUser1.strEmail;

            myDB.tblRequests.Remove(currRequest);
            myDB.SaveChanges(); //???

            var pi = (from T in myDB.tblUsers
                      where T.UserID == currRequest.intUserCreator
                      select T);
            var thePi = pi.Single();

            string[] lines = { "From: securecms@polynubstudios.com", "To: " + thePi.strEmail, "Subject: New Project denied", "Your project has been denied by " + user.strFirstName + " " + user.strLastName, "." };

            System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines);

            return Redirect("/ControlPanel/Approver");


        }

        public ActionResult openMyProjs()
        {
            ViewBag.blnIsPI = true;
            return Redirect("/MyProjects/Index");
        }

        public ActionResult actionStorage()
        {
            //this method is called when the action storage button is clicked
            //this changes the database to show the data has been actioned

            //Changes completed status and updates date

            //get current time
            //stick it in the correct part of the database

            tblUser user = LoginCheck(ADMINISTRATORTYPE);
            if (user == null)
            {
                return Redirect("/");
            }
            var currTime = DateTime.Now;
            var jobID = Request.Form["inputJob"];


            tblRequest currRequest = null; //Oh wait, we need this don't we?

            int id;
            tblRequest request;
            if (int.TryParse(jobID, out id))
            {
                var requests = (from r in myDB.tblRequests
                                where r.RequestID == id
                                select r);
                if (requests.Count() == 0)
                    throw new Exception("No matching requests");
                else
                    request = requests.First();
            }
            else
                throw new Exception("Can't parse form. Something is very wrong with your browser. Are you using IE6 or something?");
            currRequest = request; //BWA HAHAHAHAHA


            if (currRequest == null)
            {
                return Redirect("/ControlPanel/Admin"); // This should go to an error page. You there! Programmer! Error Page! :)
            }

            if(currRequest.ProjectID == null)
            {
                AddProj("New Project", currRequest.intUserCreator, currRequest.intUserCreator, currRequest.intRequestSize); //Wham

                var pi = (from T in myDB.tblUsers
                            where T.UserID == currRequest.intUserCreator
                            select T);
                var theUser = pi.First();
                string[] lines = { "From: securecms@polynubstudios.com", "To: " + theUser.strEmail, "Subject: Your project has been approved", "Your project storage has been approved", "." };

                System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines);
            }
            else
            {
                
                UpdateProj(Convert.ToInt32(currRequest.ProjectID),currRequest.intRequestSize,false); //And now it auto actions. Sysadmins, thank me later.

                var project = (from T in myDB.tblProjects
                               where T.ProjectID == currRequest.ProjectID
                               select T);
                var theProject = project.First();

                var pi = (from T in myDB.tblUsers
                          where T.UserID == theProject.intPrimaryInv
                          select T);
                var thePi = pi.First();

                var dm = (from T in myDB.tblUsers
                          where T.UserID == theProject.intDataManager
                          select T);
                var theDm = dm.First();

                if (theDm.UserID == thePi.UserID)
                {
                    string[] lines = { "From: securecms@polynubstudios.com", "To: " + thePi.strEmail + "," + theDm.strEmail, "Subject: Additional storage request approved", "Your additional storage for " + theProject.strProjectName + " has been approved", "." };
                    System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines);
                }
                else
                {
                    string[] lines = { "From: securecms@polynubstudios.com", "To: " + thePi.strEmail + "," + theDm.strEmail, "Subject: Additional storage request approved", "Your additional storage for " + theProject.strProjectName + " has been approved", "." };
                    System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines);
                }
            }

            //Now we have the job in question. Hooray. And I is the right number :D
            currRequest.intUserActioner = user.UserID;
            currRequest.dtmCompleted = currTime;

            UpdateModel(currRequest);
            myDB.SaveChanges(); //???

            var Approver = (from T in myDB.tblUsers
                                         where T.UserID == currRequest.intUserApprover
                                         select T);

            var theApprover = Approver.Single();

            string[] lines2 = { "From: securecms@polynubstudios.com", "To: " + theApprover.strEmail, "Subject: New Project created", "Your project has been actioned by the administrator", "." };

            System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines2);



            // myDB.Entry()
            // myDB.Entry(item).State = System.Data.EntityState.Modified;
            // myDB.SaveChanges();
            return Redirect("/ControlPanel/Admin");


        }

        public ActionResult AddProjectForm()
        {
            var possibleUserList = (from u in myDB.tblUsers
                                    where u.UserTypeID == PRIMARYINVTYPE || u.UserTypeID == DATAMANAGERTYPE || u.UserTypeID == RESEARCHERTYPE
                                    select u);
            ViewBag.userlist = possibleUserList.ToList();
            return View();
        }
        
        //PRIMARY INV
        public ActionResult PrimInv()
        {
            HttpCookie theCookie = Request.Cookies["loginCookie"];
            int key = Convert.ToInt32(theCookie.Value);
        tblUser myUser = LoginCheck(PRIMARYINVTYPE);
            if (myUser == null)
            {
                myUser = LoginCheck(DATAMANAGERTYPE);
                if (myUser == null)
                {
                    myUser = LoginCheck(RESEARCHERTYPE);
                }
            }
            if (myUser == null)
            {
                return Redirect("/");
            }
            var listOfRequests = (from p in myDB.tblRequests
                                  orderby p.dtmCreated descending
                                  select p); // get this department's requests
            ViewBag.madHacks = myDB.tblRequestTypes.ToList();
            ViewBag.ListOfReqs = listOfRequests;
            ViewBag.User = myUser;
            ViewBag.UserName = myUser.strFirstName + " " + myUser.strLastName;
            //get all the projects that this user runs
            var JobsIOwn = (from p in myDB.tblProjects
                            where p.intPrimaryInv == myUser.UserID
                            select p);
            var JobsIDM = (from p in myDB.tblProjects
                           where p.intDataManager == myUser.UserID && p.intPrimaryInv != myUser.UserID
                           select p);
            List<tblProject> totalProj = JobsIOwn.ToList();
            totalProj.AddRange(JobsIDM.ToList());
            ViewBag.ProjectsIOwn = totalProj;

            return View();
        }

        //Administrator
        public ActionResult Admin()
        {
            
            tblUser myUser = LoginCheck(ADMINISTRATORTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }
            //var listOfRequests = myUser.tblDepartment.tblRequests.ToList(); // get this department's requests
            var listOfRequests = (from r in myDB.tblRequests
                                  where r.dtmApproved != null
                                  orderby r.dtmCreated descending
                                  select r);

            if (listOfRequests.Count() == 0)
            {
                throw new Exception("No requests found");
            }


            ViewBag.ListOfReqs = listOfRequests;
            ViewBag.UserName = myUser.strFirstName + " " + myUser.strLastName;
            ViewBag.Departments = myDB.tblDepartments.ToList();
            ViewBag.UserTypes = myDB.tblUserTypes.ToList();
            var awesomeR = (from p in myDB.tblUsers
                                   where p.tblUserType.UserTypeID == PRIMARYINVTYPE || p.tblUserType.UserTypeID == DATAMANAGERTYPE || p.tblUserType.UserTypeID == RESEARCHERTYPE
                                   select p);
            ViewBag.Researchers = awesomeR.ToList();
            ViewBag.Projects = myDB.tblProjects.ToList();
            var awesomeU = (from t1 in myDB.tblUsers
                             select t1);
            ViewBag.Users = awesomeU.ToList();
            ViewBag.Length = awesomeU.Count();
            
            return View();
        }

        public ActionResult AdminChangePrimaryInv()
        {
            var myUser = LoginCheck(ADMINISTRATORTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }
            var tempProj = new tblProject();
            var currProj = Convert.ToInt32(Request.Form["selectedProj"]);
            var newPrimaryInv = Convert.ToInt32(Request.Form["newPrimaryInv"]);

            var theProj = (from p in myDB.tblProjects
                           where p.ProjectID == currProj
                           select p);
           
            var theProj2 = theProj.Single();
            tempProj = theProj2;
            if (theProj2.intDataManager == theProj2.intPrimaryInv)
            {
                tempProj.intPrimaryInv = newPrimaryInv;
                tempProj.intDataManager = newPrimaryInv;
            }
            else 
            {
                tempProj.intPrimaryInv = newPrimaryInv;
            }
            UpdateModel(tempProj);
            myDB.SaveChanges();
            return Redirect("/ControlPanel/Admin");
        }

        public ActionResult AdminRemoveUser()
        {
            var myUser = LoginCheck(ADMINISTRATORTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }
            var currUser =  Convert.ToInt32(Request.Form["selectedUser"]);
            // gets all reqs where user is creator
            var reqsToRemove = (from p in myDB.tblRequests
                               where p.intUserCreator == currUser
                               select p);

            // gets all projects where user is PI
            var projectsToRemove = (from p in myDB.tblProjects
                                    where p.intPrimaryInv == currUser
                                    select p);
            
            // gets all projects where user is dataManager
            var dataManagersToRemove = (from p in myDB.tblProjects
                                        where p.intDataManager == currUser && p.intPrimaryInv != currUser
                                        select p);
            //get user to delete durr
            var userToRemove = (from p in myDB.tblUsers
                                where p.UserID == currUser
                                select p);

            var userToRemove2 = userToRemove.Single();
            var reqsToRemove2 = reqsToRemove.ToList();
            var projectsToRemove2 = projectsToRemove.ToList();
            var dataManagersToRemove2 = dataManagersToRemove.ToList();

            foreach(var item in reqsToRemove2)
            {
                myDB.tblRequests.Remove(item);
               //todo archive
            }

            foreach (var item in projectsToRemove2)
            {
                //RemoveProject(item.ProjectID);
            }

            foreach (var item in dataManagersToRemove2)
            {
                item.intDataManager = item.intPrimaryInv;
                string[] lines = { "From: securecms@polynubstudios.com", "To: " + item.DM.strEmail, "Subject: You have been promoted!!!", "You have been made the DataManager of one of your projects", "." };
                System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines);
                //todo archive
            }
            //var piEmail = dataManagersToRemove;
            var userEmail = userToRemove2.strEmail;
            myDB.tblUsers.Remove(userToRemove2);
            myDB.SaveChanges();
            
            string[] lines2 = { "From: securecms@polynubstudios.com", "To: " + userEmail, "Subject: New Project created", "Your project has been actioned by the administrator", "." };
            System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines2);

            return Redirect("/ControlPanel/Admin");
        }

        public ActionResult AdminAddUser()
        {
            var myUser = LoginCheck(ADMINISTRATORTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }

            tblUser newUser = new tblUser();

            newUser.strFirstName = Request.Form["newUserFirstName"];
            newUser.strLastName = Request.Form["newUserLastName"];
            newUser.strEmail = Request.Form["newUserName"];
            newUser.strPassword = Request.Form["newUserPassword"];
            newUser.DepartmentID = Convert.ToInt32(Request.Form["newUserDepartmentID"]);
            newUser.UserTypeID = Convert.ToInt32(Request.Form["newUserTypeID"]);

            myDB.tblUsers.Add(newUser);

            myDB.SaveChanges();

            return Redirect("/ControlPanel/Admin");
        }

        public ActionResult emailUser()
        {
            var myUser = LoginCheck(ADMINISTRATORTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }

            string[] lines = { "From: test2@polynubstudios.com", "To: twunknown@gmail.com", "Subject: Email admin test", "email from admin", "." };

            System.IO.File.WriteAllLines(@"C:\inetpub\mailroot\Pickup\email.txt", lines);

            return Redirect("/ControlPanel/Admin");
        }

        protected tblProject UpdateProj(int projectID, int sizeIncrease, bool setFactor)
        {
            var updateProj = (from p in myDB.tblProjects
                              where p.ProjectID == projectID
                              select p);
            var theProj = updateProj.Single();//UID, therefore there is only one
            if(setFactor)
            {
                theProj.intStorageSize = sizeIncrease;
            }
            else
            {
                theProj.intStorageSize = theProj.intStorageSize + sizeIncrease;
            }

            UpdateModel(theProj);
            myDB.SaveChanges();
            
            return theProj;
        }

        protected tblProject AddProj(string ProjectName, int PrimInvID, int DMID, int storageSize)
        {
            tblProject proj = new tblProject();

            proj.strProjectName = ProjectName;
            proj.intPrimaryInv = PrimInvID;
            proj.intDataManager = DMID;
            proj.intStorageSize = storageSize;

            myDB.tblProjects.Add(proj);
            myDB.SaveChanges();

            return proj;
        }

        public ActionResult AdminAddProject()
        {
            var myUser = LoginCheck(ADMINISTRATORTYPE);
            if(myUser == null)
            {
                return Redirect("/");
            }

            tblProject proj = new tblProject();

            proj = AddProj(Request.Form["newProjectName"], Convert.ToInt32(Request.Form["newProjectOwner"]), proj.intPrimaryInv, Convert.ToInt32(Request.Form["newProjectSize"]));

            //But how do we find it again? By being a hacky bastard.

            var theThingWeWant = (from p in myDB.tblProjects
                                  where p.strProjectName == proj.strProjectName && p.intPrimaryInv == proj.intPrimaryInv && p.intDataManager == proj.intDataManager && p.intStorageSize == proj.intStorageSize
                                  orderby p.ProjectID descending
                                  select p);
            //Yes, this very well could be a list of things, however, we know it will be the one with the largest ID, and we *know* that it always sorts the results by the ID. So...
            var theOneWeWant = theThingWeWant.First();

            var listOfUser = (from u in myDB.tblUsers
                                  where u.UserID == proj.intPrimaryInv
                                  select u);
            var userWeWant = listOfUser.First();
            tblProjectResearcher newResearcher = new tblProjectResearcher();
            newResearcher.ProjectID = theOneWeWant.ProjectID;
            newResearcher.UserID = userWeWant.UserID;
            newResearcher.blnIsDM = 1;
            newResearcher.blnIsPI = 1;

            myDB.tblProjectResearchers.Add(newResearcher);
            myDB.SaveChanges();

            return Redirect("/ControlPanel/Admin");
        }

        public ActionResult AdminRemoveProject()
        {
            int projectID = Convert.ToInt32(Request.Form["selectedProject"]);

            DeleteProject(projectID);

            return Redirect("/ControlPanel/Admin");
        }

        protected void DeleteProject(int projectID)
        {
            var allUsers = (from v in myDB.tblProjectResearchers
                            where v.ProjectID == projectID
                            select v);
            var project = (from p in myDB.tblProjects
                           where p.ProjectID == projectID
                           select p);
            var ListUsr = allUsers.ToList();
            var TheProj = project.Single();

            foreach(var item in ListUsr)
            {
                myDB.tblProjectResearchers.Remove(item);
            }
            myDB.tblProjects.Remove(TheProj);
            myDB.SaveChanges();
        }

        public ActionResult NewRequestData()
        {
            //this method is called when the primary investigator storage button is clicked
            //this creates a request for new storage space

            //changes item.approved and approval date
            //but not completed

            //get current time
            //stick it in the correct part of the database

            tblUser user = LoginCheck(PRIMARYINVTYPE);
            if (user == null)
            {
                return Redirect("/");
            }
            var currTime = DateTime.Now;
            var storageSize = Request.Form["storageSize"];
            var requestType = Request.Form["requestType"];
            var comment = Request.Form["theComment"];
            var userID = user.UserID;
            var departmentID = user.DepartmentID;
           

            //tblRequestType currRequestType = null;
            tblRequest currRequest = new tblRequest();
            currRequest.DepartmentID = departmentID;
            currRequest.dtmApproved = null;
            currRequest.dtmCompleted = null;
            currRequest.dtmCreated = currTime;
            currRequest.intUserCreator = userID;
            currRequest.intUserApprover = null;
            currRequest.intUserActioner = null;
            currRequest.Comments = comment;
            currRequest.RequestType = Convert.ToInt32(requestType);
            //currRequestType.strRequestInfo = storageInfo;
            //currRequestType.strRequestName = requestType; What? o.o;
            currRequest.intRequestSize = Convert.ToInt32(storageSize);
            // myDB.tblRequestTypes.Add(currRequestType);           
            myDB.tblRequests.Add(currRequest);
            try
            {
                myDB.SaveChanges();
            }
            catch (Exception E)
            {
                Response.Write("Oh shit a problem " + E.Message);
            }
            //if(errorpage)
            //{
            //  throw new Exception("Can't parse form. Something is very wrong with your browser. Are you using IE6 or something?");
            //}  
            return Redirect("/ControlPanel/PrimInv");
        }
        
        public ActionResult ModifyCommentApprover()
        {
            var myUser = LoginCheck(APPROVERTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }
            var theReq = Convert.ToInt32(Request.Form["theReq"]);
            var theComment = Request.Form["theComment"];
            
            tblRequest modifyReq = new tblRequest();

            var theActualReq = (from p in myDB.tblRequests
                                      where p.RequestID == theReq
                                      select p).Single();
            theActualReq.Comments = theComment;
            myDB.SaveChanges();
            return Redirect("/ControlPanel/Approver");
        }

        public ActionResult ModifyCommentPrimInv()
        {
            var myUser = LoginCheck(PRIMARYINVTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }
            var theReq = Convert.ToInt32(Request.Form["theReq"]);
            var theComment = Request.Form["theComment"];
            
            tblRequest modifyReq = new tblRequest();

            var theActualReq = (from p in myDB.tblRequests
                                      where p.RequestID == theReq
                                      select p).Single();
            theActualReq.Comments = theComment;
            myDB.SaveChanges();
            return Redirect("/ControlPanel/PrimInv");
        }

        public ActionResult ModifyCommentAdmin()
        {
            var myUser = LoginCheck(ADMINISTRATORTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }
            var theReq = Convert.ToInt32(Request.Form["theReq"]);
            var theComment = Request.Form["theComment"];

            tblRequest modifyReq = new tblRequest();

            var theActualReq = (from p in myDB.tblRequests
                                where p.RequestID == theReq
                                select p).Single();
            theActualReq.Comments = theComment;
            myDB.SaveChanges();
            return Redirect("/ControlPanel/Admin");
        }

        public ActionResult AdminAddSchool()
        {
            var myUser = LoginCheck(ADMINISTRATORTYPE);
            if (myUser == null)
            {
                return Redirect("/");
            }

            var schoolName = Request.Form["newSchoolName"];
            var schoolUserName = Request.Form["newUserName"];
            var schoolUserFirstName = Request.Form["newUserFirstName"];
            var schoolUserPassword = Request.Form["newUserPassword"];
            var schoolUserLastName = Request.Form["newUserLastName"];
            var schoolUserTypeID = Request.Form["newUserTypeID"];

            tblUser newUser = new tblUser();

            newUser.strFirstName = schoolUserFirstName;
            newUser.strLastName = schoolUserLastName;
            newUser.strEmail = schoolUserName;
            newUser.strPassword = schoolUserPassword;
            newUser.DepartmentID = 0;
            newUser.UserTypeID = Convert.ToInt32(schoolUserTypeID);

            myDB.tblUsers.Add(newUser);
            myDB.SaveChanges();

            var schoolessApprovers = (from p in myDB.tblUsers
                                     where p.tblUserType.UserTypeID == APPROVERTYPE && p.DepartmentID == 0 && p.strFirstName == schoolUserFirstName && p.strLastName == schoolUserLastName 
                                    select p);
            var theApprover = schoolessApprovers.Single();

            var userInQuestion = theApprover.UserID;

            tblDepartment newDept = new tblDepartment();
            //newDept.departmentID = ; is done for us.
            newDept.strDepartmentName = schoolName;
            newDept.intApprover = userInQuestion;
            myDB.tblDepartments.Add(newDept);
            myDB.SaveChanges();

            var schools = (from p in myDB.tblDepartments
                           where p.strDepartmentName == schoolName && p.intApprover == userInQuestion
                           select p);
            var schoolessApprovers2 = (from p in myDB.tblUsers
                                       where p.tblUserType.UserTypeID == APPROVERTYPE && p.DepartmentID == 0 && p.strFirstName == schoolUserFirstName && p.strLastName == schoolUserLastName
                                       select p);
            var theApprover2 = schoolessApprovers2.Single();
            var theSchool = schools.Single();
            theApprover2.DepartmentID = theSchool.DepartmentID;

            myDB.SaveChanges();

            return Redirect("/ControlPanel/Admin");
        }
    }
}

